import { View, Text, Button, Input } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import './ding.scss'

// 平台检测函数
const isH5 = () => {
  return process.env.TARO_ENV === 'h5'
}

const isMiniProgram = () => {
  return process.env.TARO_ENV === 'weapp'
}

// 获取API基础URL
const getApiBaseUrl = () => {
  if (isH5()) {
    // H5环境下使用代理路径，避免跨域问题
    return process.env.NODE_ENV === 'development' 
      ? '/api' 
      : 'https://your-production-api.com'
  }
  // 小程序环境使用原有的IP地址
  return 'http://192.168.8.53:3000'
}

interface OrderInfo {
  _id: string
  orderNumber: string
  customerInfo: {
    name: string
    phone: string
    address: string
  }
  deviceInfo: {
    type: string
    problem: string
  }
  status: string
  createdAt: string
  updatedAt: string
  cost: number
  notes?: string
  paid?: boolean
}

export default function Ding() {
  const [searchType, setSearchType] = useState<'phone' | 'orderNumber'>('phone')
  const [searchValue, setSearchValue] = useState('')
  const [orders, setOrders] = useState<OrderInfo[]>([])
  const [loading, setLoading] = useState(false)
  const [hasSearched, setHasSearched] = useState(false)

  const statusMap = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '维修中',
    completed: '已完成',
    cancelled: '已取消'
  }

  // 显示提示信息的兼容函数
  const showToast = (title: string, icon: 'success' | 'none' = 'none') => {
    if (isH5()) {
      // H5环境使用原生alert或自定义提示
      alert(title)
    } else {
      // 小程序环境使用Taro.showToast
      Taro.showToast({
        title,
        icon,
        duration: 2000
      })
    }
  }

  // 显示模态框的兼容函数
  const showModal = (title: string, content: string, onConfirm: () => void) => {
    if (isH5()) {
      // H5环境使用原生confirm
      if (confirm(`${title}\n\n${content}`)) {
        onConfirm()
      }
    } else {
      // 小程序环境使用Taro.showModal
      Taro.showModal({
        title,
        content,
        success: (res) => {
          if (res.confirm) {
            onConfirm()
          }
        }
      })
    }
  }

  // 显示加载中的兼容函数
  const showLoading = (title: string) => {
    if (isH5()) {
      // H5环境可以使用console.log或自定义loading
      console.log(`Loading: ${title}`)
    } else {
      // 小程序环境使用Taro.showLoading
      Taro.showLoading({ title })
    }
  }

  // 隐藏加载中的兼容函数
  const hideLoading = () => {
    if (isH5()) {
      // H5环境不需要特殊处理
      console.log('Loading finished')
    } else {
      // 小程序环境使用Taro.hideLoading
      Taro.hideLoading()
    }
  }

  // 网络请求的兼容函数
  const makeRequest = async (url: string) => {
    if (isH5()) {
      // H5环境使用fetch
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'content-type': 'application/json'
        }
      })
      const data = await response.json()
      return { data }
    } else {
      // 小程序环境使用Taro.request
      return await Taro.request({
        url,
        method: 'GET',
        header: {
          'content-type': 'application/json'
        }
      })
    }
  }

  // 支付请求的兼容函数
  const makePaymentRequest = async (url: string, data: any, method: string = 'POST') => {
    if (isH5()) {
      // H5环境使用fetch
      const response = await fetch(url, {
        method: method,
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      const responseData = await response.json()
      return { data: responseData }
    } else {
      // 小程序环境使用Taro.request
      return await Taro.request({
        url,
        method: method as any,
        data,
        header: {
          'content-type': 'application/json'
        }
      })
    }
  }

  const handleSearch = async () => {
    if (!searchValue.trim()) {
      showToast(searchType === 'phone' ? '请输入手机号' : '请输入订单号')
      return
    }

    setLoading(true)
    setHasSearched(true)
    try {
      let url = ''
      if (searchType === 'phone') {
        url = `${getApiBaseUrl()}/zpf/orders/phone/${searchValue.trim()}`
      } else {
        url = `${getApiBaseUrl()}/zpf/orders/${searchValue.trim()}`
      }

      const response = await makeRequest(url)

      if (response.data.success) {
        if (searchType === 'phone') {
          const ordersWithPaymentStatus = (response.data.data || []).map(order => ({
            ...order,
            paid: order.paid || false
          }))
          setOrders(ordersWithPaymentStatus)
        } else {
          const orderData = response.data.data ? {
            ...response.data.data,
            paid: response.data.data.paid || false
          } : null
          setOrders(orderData ? [orderData] : [])
        }
      } else {
        setOrders([])
        showToast(response.data.message || '查询失败')
      }
    } catch (error) {
      console.error('查询订单失败:', error)
      setOrders([])
      showToast('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const handlePayment = async (order: OrderInfo) => {
    if (!order.cost || order.cost <= 0) {
      showToast('订单金额异常')
      return
    }

    showModal(
      '确认支付',
      `订单号：${order.orderNumber}\n维修费用：¥${order.cost}\n\n确认支付吗？`,
      async () => {
        showLoading('支付中...')
        
        try {
          const response = await makePaymentRequest(
            `${getApiBaseUrl()}/zpf/pay-order`,
            {
              orderId: order._id,
              orderNumber: order.orderNumber,
              amount: order.cost
            }
          )
          
          hideLoading()
          
          if (response.data.success) {
            showToast('支付成功', 'success')
            
            // 更新订单状态
            setOrders(prevOrders => 
              prevOrders.map(o => 
                o._id === order._id ? { ...o, paid: true } : o
              )
            )
          } else {
            showToast(response.data.message || '支付失败')
          }
        } catch (error) {
          hideLoading()
          console.error('支付失败:', error)
          showToast('网络错误，请稍后重试')
        }
      }
    )
  }

  const handleConfirmOrder = async (order: OrderInfo) => {
    // H5环境简化流程
    if (isH5()) {
      const costInput = prompt('请输入维修费用（元）：')
      if (!costInput) return
      
      const cost = parseFloat(costInput)
      if (isNaN(cost) || cost < 0) {
        showToast('请输入有效的费用金额')
        return
      }
      
      const paid = confirm(`维修费用：¥${cost}\n\n是否已收取费用？`)
      
      showLoading('确认中...')
      
      try {
        const response = await makePaymentRequest(
          `${getApiBaseUrl()}/zpf/order/${order.orderNumber}/confirm`,
          {
            cost: cost,
            paid: paid
          },
          'PUT'
        )
        
        hideLoading()
        
        if (response.data.success) {
          showToast('订单确认成功', 'success')
          
          // 更新订单状态
          setOrders(prevOrders => 
            prevOrders.map(o => 
              o._id === order._id ? { 
                ...o, 
                status: 'confirmed',
                cost: cost,
                paid: paid
              } : o
            )
          )
        } else {
          showToast(response.data.message || '确认订单失败')
        }
      } catch (error) {
        hideLoading()
        console.error('确认订单失败:', error)
        showToast('网络错误，请稍后重试')
      }
    } else {
      // 小程序环境保持原有逻辑
      Taro.showModal({
        title: '设置维修费用',
        content: '请输入维修费用（元）',
        editable: true,
        placeholderText: '请输入费用',
        success: async (res) => {
          if (res.confirm) {
            const cost = parseFloat(res.content || '0')
            
            if (isNaN(cost) || cost < 0) {
              Taro.showToast({
                title: '请输入有效的费用金额',
                icon: 'none',
                duration: 2000
              })
              return
            }
            
            Taro.showModal({
              title: '确认订单',
              content: `维修费用：¥${cost}\n\n是否已收取费用？`,
              confirmText: '已收费',
              cancelText: '未收费',
              success: async (payRes) => {
                const paid = payRes.confirm
                
                Taro.showLoading({ title: '确认中...' })
                
                try {
                  const response = await Taro.request({
                    url: `${getApiBaseUrl()}/zpf/order/${order.orderNumber}/confirm`,
                    method: 'PUT',
                    data: {
                      cost: cost,
                      paid: paid
                    },
                    header: {
                      'content-type': 'application/json'
                    }
                  })
                  
                  Taro.hideLoading()
                  
                  if (response.data.success) {
                    Taro.showToast({
                      title: '订单确认成功',
                      icon: 'success',
                      duration: 2000
                    })
                    
                    setOrders(prevOrders => 
                      prevOrders.map(o => 
                        o._id === order._id ? { 
                          ...o, 
                          status: 'confirmed',
                          cost: cost,
                          paid: paid
                        } : o
                      )
                    )
                  } else {
                    Taro.showToast({
                      title: response.data.message || '确认订单失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                } catch (error) {
                  Taro.hideLoading()
                  console.error('确认订单失败:', error)
                  Taro.showToast({
                    title: '网络错误，请稍后重试',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          }
        }
      })
    }
  }

  const handleCancelOrder = async (order: OrderInfo) => {
    if (isH5()) {
      // H5环境简化流程
      const reason = prompt('请输入取消原因（可选）：') || ''
      
      if (!confirm('确认取消订单吗？')) return
      
      showLoading('取消中...')
      
      try {
        const response = await makePaymentRequest(
          `${getApiBaseUrl()}/zpf/order/${order.orderNumber}/cancel`,
          {
            reason: reason
          },
          'PUT'
        )
        
        hideLoading()
        
        if (response.data.success) {
          showToast('订单取消成功', 'success')
          
          // 更新订单状态
          setOrders(prevOrders => 
            prevOrders.map(o => 
              o._id === order._id ? { 
                ...o, 
                status: 'cancelled',
                notes: reason ? `取消原因：${reason}` : '订单已取消'
              } : o
            )
          )
        } else {
          showToast(response.data.message || '取消订单失败')
        }
      } catch (error) {
        hideLoading()
        console.error('取消订单失败:', error)
        showToast('网络错误，请稍后重试')
      }
    } else {
      // 小程序环境保持原有逻辑
      Taro.showModal({
        title: '取消订单',
        content: '请输入取消原因（可选）',
        editable: true,
        placeholderText: '请输入取消原因',
        success: async (res) => {
          if (res.confirm) {
            Taro.showLoading({ title: '取消中...' })
            
            try {
              const response = await Taro.request({
                url: `${getApiBaseUrl()}/zpf/order/${order.orderNumber}/cancel`,
                method: 'PUT',
                data: {
                  reason: res.content || ''
                },
                header: {
                  'content-type': 'application/json'
                }
              })
              
              Taro.hideLoading()
              
              if (response.data.success) {
                Taro.showToast({
                  title: '订单取消成功',
                  icon: 'success',
                  duration: 2000
                })
                
                // 更新订单状态
                setOrders(prevOrders => 
                  prevOrders.map(o => 
                    o._id === order._id ? { 
                      ...o, 
                      status: 'cancelled',
                      notes: res.content ? `取消原因：${res.content}` : '订单已取消'
                    } : o
                  )
                )
              } else {
                Taro.showToast({
                  title: response.data.message || '取消订单失败',
                  icon: 'none',
                  duration: 2000
                })
              }
            } catch (error) {
              Taro.hideLoading()
              console.error('取消订单失败:', error)
              Taro.showToast({
                title: '网络错误，请稍后重试',
                icon: 'none',
                duration: 2000
              })
            }
          }
        }
      })
    }
  }

  const goBack = () => {
    if (isH5()) {
      // H5环境下优先使用浏览器返回
      if (window.history.length > 1) {
        Taro.navigateBack()
      } else {
        Taro.navigateTo({
          url: '/pages/index/index'
        })
      }
    } else {
      // 小程序环境
      Taro.navigateBack()
    }
  }

  return (
    <View className={`ding-container ${isH5() ? 'h5-platform' : 'miniprogram-platform'}`}>
      <View className="header">
        <Text className="title">订单查询</Text>
        <Button className="back-btn" onClick={goBack}>返回</Button>
      </View>

      <View className="search-container">
        <View className="search-type">
          <Button 
            className={`type-btn ${searchType === 'phone' ? 'active' : ''}`}
            onClick={() => {
              setSearchType('phone')
              setSearchValue('')
              setOrders([])
              setHasSearched(false)
            }}
          >
            手机号查询
          </Button>
          <Button 
            className={`type-btn ${searchType === 'orderNumber' ? 'active' : ''}`}
            onClick={() => {
              setSearchType('orderNumber')
              setSearchValue('')
              setOrders([])
              setHasSearched(false)
            }}
          >
            订单号查询
          </Button>
        </View>

        <View className="search-input">
          <Input
            className="input"
            placeholder={searchType === 'phone' ? '请输入手机号' : '请输入订单号'}
            value={searchValue}
            onInput={(e) => setSearchValue(e.detail.value)}
          />
          <Button 
            className="search-btn" 
            onClick={handleSearch}
            loading={loading}
          >
            {loading ? '查询中...' : '查询'}
          </Button>
        </View>
      </View>

      <View className="orders-container">
        {hasSearched && (
          <>
            {orders.length > 0 ? (
              <>
                <Text className="result-title">
                  {searchType === 'phone' ? '您的订单列表' : '订单详情'}
                </Text>
                {orders.map((order) => (
                  <View key={order._id} className="order-card">
                    <View className="order-header">
                      <Text className="order-number">订单号：{order.orderNumber}</Text>
                      <Text className={`order-status status-${order.status}`}>
                        {statusMap[order.status] || order.status}
                      </Text>
                    </View>
                    
                    <View className="order-info">
                      <View className="info-row">
                        <Text className="label">客户姓名：</Text>
                        <Text className="value">{order.customerInfo.name}</Text>
                      </View>
                      <View className="info-row">
                        <Text className="label">联系电话：</Text>
                        <Text className="value">{order.customerInfo.phone}</Text>
                      </View>
                      {order.customerInfo.address && (
                        <View className="info-row">
                          <Text className="label">服务地址：</Text>
                          <Text className="value">{order.customerInfo.address}</Text>
                        </View>
                      )}
                      <View className="info-row">
                        <Text className="label">设备类型：</Text>
                        <Text className="value">{order.deviceInfo.type}</Text>
                      </View>
                      <View className="info-row">
                        <Text className="label">故障描述：</Text>
                        <Text className="value problem">{order.deviceInfo.problem}</Text>
                      </View>
                      <View className="info-row">
                        <Text className="label">创建时间：</Text>
                        <Text className="value">{formatDate(order.createdAt)}</Text>
                      </View>
                      <View className="info-row">
                        <Text className="label">维修费用：</Text>
                        <Text className="value cost">
                          {order.cost > 0 ? `¥${order.cost}` : '待定'}
                        </Text>
                      </View>
                      <View className="info-row">
                        <Text className="label">支付状态：</Text>
                        <Text className={`value ${order.paid ? 'paid' : 'unpaid'}`}>
                          {order.paid ? '已支付' : '未支付'}
                        </Text>
                      </View>
                      {order.status === 'pending' && (
                        <View className="action-section">
                          <Button 
                            className="confirm-btn" 
                            onClick={() => handleConfirmOrder(order)}
                          >
                            确认订单
                          </Button>
                          <Button 
                            className="cancel-btn" 
                            onClick={() => handleCancelOrder(order)}
                          >
                            取消订单
                          </Button>
                        </View>
                      )}
                      {!order.paid && order.cost > 0 && (order.status === 'pending' || order.status === 'confirmed' || order.status === 'in_progress') && (
                        <View className="payment-section">
                          <Button 
                            className="pay-btn" 
                            onClick={() => handlePayment(order)}
                          >
                            立即支付 ¥{order.cost}
                          </Button>
                        </View>
                      )}
                      {order.notes && (
                        <View className="info-row">
                          <Text className="label">备注：</Text>
                          <Text className="value">{order.notes}</Text>
                        </View>
                      )}
                    </View>
                  </View>
                ))}
              </>
            ) : (
              <View className="no-orders">
                <Text className="no-orders-text">
                  {searchType === 'phone' ? '暂无订单记录' : '订单不存在'}
                </Text>
                <Text className="no-orders-tip">
                  {searchType === 'phone' 
                    ? '请确认手机号是否正确，或联系客服咨询' 
                    : '请确认订单号是否正确'}
                </Text>
              </View>
            )}
          </>
        )}
      </View>
    </View>
  )
}